<template>
  <base-modal :title="modalTitle" :show.sync="remindCustomerDialog" width="500px" class="batch-remind-customer-dialog" @closed="reset">
    <el-form label-width="80px" ref="form" :model="form" :rules="rules">

      <el-form-item :label="$t('product.detail.remindDialog.type.remindId')" prop="remindId">
        <el-select v-model="form.remindId" :placeholder="$t('product.detail.remindDialog.placeholder.remindId')" @change="updateFormUser">
          <el-option v-for="item in remindTemplate" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="selectedRemind.sendWay !== 1" :label="$t('common.bizComponents.bizBatchRemind.form.content')" class="content-item">
        {{selectedRemind.content}}
      </el-form-item>
      <el-form-item :label="$t('product.detail.remindDialog.type.remindRule')">
        {{remindRule}}
      </el-form-item>
      <el-form-item v-show="selectedRemind.sendWay === 1 && !selectedRemind.isDdResponse" :label="$t('common.bizComponents.bizSendEmail.label.subject')">
        {{selectedRemind.emailTitle}}
      </el-form-item>
      <el-form-item v-show="selectedRemind.sendWay === 1 && !selectedRemind.isDdResponse" :label="$t('common.base.emailContent')" class="content-item">
        {{selectedRemind.emailContent}}
      </el-form-item>
      <el-form-item :label="$t('common.bizComponents.bizBatchRemind.form.user')">
        
        <base-select-user-input
          class="base-select-user-input-item"
          :placeholder="$t('product.detail.remindDialog.placeholder.users')"
          multiple 
          :collapse="false"
          :error="error"
          v-model="form.users" 
          @input="validateUser"
          v-if="selectedRemind.isDdResponse"
        >
        </base-select-user-input>
        
        <base-select
          v-else
          v-model="form.users"
          :remote-method="searchManager"
          @input="validateUser"
          multiple
          clearable
          :is-use-value="Boolean(selectedRemind.isDdResponse)"
          :error="error"
          :placeholder="$t('product.detail.remindDialog.placeholder.users')"
        >
          <template slot="option" slot-scope="{option}">
            <div class="initiator-option-row">
              <template v-if="isOpenData">
                <open-data type='userName' :openid="option.value || option.staffId"></open-data>
              </template>
              <template v-else>
                <span class="initiator-display-name">{{option.label}}</span>
              </template>
            </div>
          </template>
        </base-select>
        <template v-if="selectedRemind.isDdResponse && hasBindCustomer">
          <span style="display: inline-block; margin-top: 10px;">{{$t('product.detail.remindDialog.text.text1')}}：</span>
          <el-checkbox-group :value="sendRoleSetting" @input="change" style="display:inline">
            <el-checkbox label="sendToCustomerExecutor">{{$t('product.detail.remindDialog.text.text2')}}</el-checkbox>
            <el-checkbox label="sendToCustomerTag">{{$t('product.detail.remindDialog.text.text3')}}</el-checkbox>
          </el-checkbox-group>
        </template>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <remind-icon></remind-icon>

      <el-button @click="remindCustomerDialog = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="onSubmit" :disabled="pending">{{$t('common.base.makeSure')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
import { isOpenData } from '@src/util/platform';
import _ from 'lodash';
import Page from '@model/Page';
import { getProductRemindTemplate } from '@src/api/ProductApi';
import * as CustomerApi from '@src/api/CustomerApi.ts';
import { createScheduler, editScheduler} from '@src/api/CommonApi'

import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser'
import RemindIcon from '@src/modules/customer/list/operationDialog/RemindIcon.vue';
import { t } from '@src/locales'
import { getSettingRemindFieldList } from '@src/api/SettingApi'

export default {
  name: 'remind-dialog',
  data() {
    return {
      isOpenData,
      sendRoleSetting: [],
      linkmanListOfCustomer: [],
      remindTemplate: [],
      form: {
        remindId: null,
        users: [],
      },
      remindCustomerDialog: false,
      pending: false,
      error: false,
      init: false,
      editedRemind: {},
      rules: {
        remindId: [{ required: true, message: this.$t('product.detail.remindDialog.text.text4'), trigger: 'change' }]
      },
      fieldList: []
    }
  },
  props: {
    product: {
      type: Object,
      default: () => ({}),
    },
     modal: {
      required: true,
      type: String,
      validator: function(value) {
        return ['customer', 'product'].includes(value);
      }
    }
  },
  computed: {
    action() {
      return this.editedRemind.id ? 'edit' : 'create';
    },
    modalTitle() {
      return this.editedRemind.id ? this.$t('product.detail.remindDialog.editRemind') : this.$t('product.detail.remindDialog.addRemind');
    },
    fieldNameMap() {
      return this.fieldList.reduce((acc, cur) => {
        acc[cur.fieldName] = cur.displayName;
        return acc;
      }, {})
    },
    selectedRemind() {
      return this.remindTemplate.filter(rt => rt.id === this.form.remindId)[0] || {};
    },
    remindRule() {
      let { isRepeat, period, fieldName, fieldDisplayName, isAhead, hours, periodUnit, timeUnit, } = this.selectedRemind;
      let unit = periodUnit === 'day' ? this.$t('common.time.day') : (periodUnit === 'week' ? this.$t('common.time.week') : this.$t('common.time.month'));
      let isahead = isAhead ? this.$t('common.base.before') : this.$t('common.base.after');
      let dorh = (timeUnit == 'hour' || !timeUnit) ? this.$t('common.time.hour') : this.$t('common.time.day');

      const displayFieldName = this.fieldNameMap[fieldName]
      fieldDisplayName = displayFieldName || fieldDisplayName

      if (!isRepeat){
        if(fieldDisplayName){
          return this.$t('product.detail.remindDialog.text.text5', { content: fieldDisplayName + (isahead + hours) + dorh });
        }
        return this.$t('common.base.nothing')
        
      }
      if(period){
        return this.$t('product.detail.remindDialog.text.text6', { content: fieldDisplayName + (isahead + hours) + dorh, time: period + unit });
      }
      return this.$t('common.base.nothing')

    },
    hasBindCustomer() {
      return !!this.product.customer?.id
    }
  },
  components: {
    RemindIcon
  },
  mounted() {
    this.getSettingRemindFieldList();
    // this.fetchData();
  },
  methods: {
    initSelect (info) {
      this.sendRoleSetting = [];
      if (info && info.sendToCustomerExecutor) this.sendRoleSetting.push('sendToCustomerExecutor');
      if (info && info.sendToCustomerTag) {
        this.sendRoleSetting.push('sendToCustomerTag')
      }
    },
    change (val) {
      this.sendRoleSetting = val;
      this.validateUser();
    },
    reset() {
      this.init = false;
      this.editedRemind = {};
      this.form = {
        remindId: null,
        users: [],
      };
      this.$emit('success-callback');
    },
    validateUser() {
      if ((!this.form.users || !this.form.users.length) && this.sendRoleSetting.length == 0) {
        // 内部提醒
        return this.error = true;
      }
      return this.error = false;
    },
    updateFormUser() {
      if(this.remindTemplate.length <= 0) return this.form.users = [];

      let users = [];
      if (this.selectedRemind.isDdResponse) {
        // 内部提醒
        if(this.selectedRemind.users) users = this.selectedRemind.users.map(({ id, name, displayName, userId }) => ({ label: name || displayName, value: id || userId }))
      } else {
        // 外部提醒（默认联系人或者全部联系人）
        if (this.selectedRemind.isDefaultLinkman) {
          users = this.linkmanListOfCustomer.filter(user => user.isMain);
        } else {
          users = this.linkmanListOfCustomer;
        }
      }

      this.initSelect(this.selectedRemind.sendRoleSetting);

      this.form.users = _.cloneDeep(users);
    },
    async onSubmit() {
      this.$refs.form.validate(valid => {
        if(!valid) return false
      })
      if (this.validateUser()) return;

      const params = this.buildParams();
      this.pending = true;
      let actionName = '';
      let fn = null;
      if (this.action === 'edit') {
        actionName = this.$t('product.detail.remindDialog.editRemind');
        fn = editScheduler;
      } else {
        fn = createScheduler;
        actionName = this.$t('product.detail.remindDialog.addRemind');
      }
      fn(params)
        .then(res => {
          if (!res.status) {
            this.$platform.notification({
              title: this.$t('common.base.success'),
              type: 'success',
              message: this.$t('product.detail.remindDialog.tips.tip1', {actionName}),
            });
          }
          if (res.status === 1 && res.data) {
            this.$platform.notification({
              title: this.$t('common.base.fail'),
              type: 'error',
              message:`${this.$t('product.detail.remindDialog.tips.tip2', {actionName})}：${res.data.join(',')}`,
            });
          }
          if (res.status === 1 && !res.data) {
            this.$platform.notification({
              title: this.$t('common.base.fail'),
              type: 'error',
              message: this.$t('product.detail.remindDialog.tips.tip3', {actionName, failContent: (res.data || res.message) && (`，${ res.data || res.message}`)}),
            });
          }
          this.remindCustomerDialog = false;
          this.pending = false;

          this.editedRemind = {};
          this.$eventBus.$emit('product_view_remind_update');
          this.$eventBus.$emit('product_remind_table.update_remind_list');
          this.$eventBus.$emit('product_info_record.update_record_list');
          // if (this.action === 'create') {
          //   this.$eventBus.$emit('customer_detail_view.select_tab', 'customer-remind-table');
          // }

        })
        .catch(err => {
          this.$platform.notification({
            title: this.$t('common.base.fail'),
            type: 'error',
            message: this.$t('product.detail.remindDialog.tips.tip4'),
          });
          this.pending = false;
          console.error('post to /scheduler/buildBatch err', err)
        });
    },
    buildParams() {
      let sendRoleSetting = {};
      sendRoleSetting.sendToCustomerExecutor = this.sendRoleSetting.indexOf('sendToCustomerExecutor') != -1;
      sendRoleSetting.sendToCustomerTag = this.sendRoleSetting.indexOf('sendToCustomerTag') != -1;
      return {
        id: this.action === 'edit' ? this.editedRemind.id : '',
        modalId: this.product.id,
        modalName: this.product.name,
        modal: 'product',
        remind: {
          id: this.form.remindId,
        },
        sendRoleSetting,
        users: (this.form.users || []).map(user => ({
          id: user.value || user.staffId || user.userId,
          name: user.label || user.displayName,
          phone: user.phone,
          email: user.email
        }))
      };
    },
    async openDialog(remind) {
      this.remindCustomerDialog = true;
      this.editedRemind = remind || {};

      await this.fetchData()
      // this.changeRemindId();

      this.hasBindCustomer && this.fetchLinkman(remind);
      this.init = true;
    },
    changeRemindId() {
      if (this.action === 'edit') {
        this.form.remindId = this.editedRemind.remind.id;
      } else {
        this.form.remindId = (this.remindTemplate[0] || {}).id;
      }
    },
    async fetchData() {
      await getProductRemindTemplate({
        hasBindCustomer: this.hasBindCustomer
      }).then(res => {
        if(!res.length) return
        this.remindTemplate = res
          .map(r => {
            r.name += `(${r.isDdResponse ? t('customer.batchRemindingCustomerDialog.remindTempName.in') : r.sendWay ? t('customer.batchRemindingCustomerDialog.remindTempName.outEmail') : t('customer.batchRemindingCustomerDialog.remindTempName.outSms')})`;
            return Object.freeze(r);
          });
        this.changeRemindId();
      })
      .catch(err => console.error('err', err));
    },
    async getSettingRemindFieldList() {
      const params = {
        modal: this.modal
      }
      const result = await getSettingRemindFieldList(params)
      const fieldList = result || []
      this.fieldList = fieldList
    },
    searchManager(params) {
      if (!this.selectedRemind.isDdResponse) {
        return Promise.resolve({
          ...new Page(),
          list: this.linkmanListOfCustomer,
          pageSize: this.linkmanListOfCustomer.length,
          pageNum: 1,
          total: this.linkmanListOfCustomer.length,
          hasNextPage: false,
        });
      }

      // params has three properties include keyword、pageSize、pageNum.
      const pms = params || {};
      return CustomerApi.getUserTag(pms)
        .then(res => {
          if (!res || !res.list) return;
          if (res.list) {
            res.list = res.list.map(user => Object.freeze({
              label: user.displayName,
              value: user.staffId,
              phone: user.cellPhone,
            }))
          }

          return res;
        })
        .catch(e => console.log(e));
    },
    fetchLinkman(remind) {
      const params = {
        customerId: this.product.customer.id,
        pageNum: 1,
        pageSize: 100000,
      };

      CustomerApi.getLinkmanOfCustomer(params)
        .then(res => {
          this.linkmanListOfCustomer = res.list
            .map(contact => {

              return Object.freeze({
                ...contact,
                label: contact.name,
                value: contact.id,
              });
            });

          if (this.action === 'create') {
            this.updateFormUser();
          } else {
            this.initSelect(remind.sendRoleSetting || {});
            this.form.users = _.cloneDeep(this.editedRemind.users).map(({id, name}) => ({label: name, value: id}))
          }
        })
        .catch(err => console.error('err', err));
    },
    chooseUser() {
      
      const users = this.form.users.map(item => {
        return {
          displayName: item.label,
          userId: item.value,
          staffId: item.staffId
        }
      })
      
      let options = {
        title: this.$t('product.detail.remindDialog.placeholder.remindId'), // [选填] 默认值为 '请选择人员'
        max: -1, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
        selectedUsers: users, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
        unique: true,
        mode: BaseSelectUserModeEnum.Filter
      }
      
      this.$fast.select.multi.user(options)
        .then((res) => {
          
          if (res.status != 0 || !res.data) return
          
          let list = res.data.users || []
          
          list = list.map(item => {
            return {
              label: item.displayName,
              value: item.userId,
              staffId: item.staffId
            }
          })
          
          this.form.users = list
          
        })
        .catch((err) => {
          console.error(err)
        })
    }
  },
}
</script>

<style lang="scss">

  .batch-remind-customer-dialog {

    .el-select .el-select__tags>span {
      display: contents;
    }

    .base-modal-body {
      padding: 10px 30px 0;
    }

    .el-form-item {
      margin: 0;
    }
    .el-radio {
      line-height: 32px;
    }

    .el-select {
      width: 100%;
    }

    .content-item {
      .el-form-item__content {
        max-height: 200px;
        overflow-y: auto;
        word-break: break-all;
      }
    }

    .dialog-footer {
      display: flex;
      justify-content: flex-end;
    }
  }

  .remind-popover {
    background: rgba(0,0,0,0.60);
    color: #fff;
    a.link {
      @include fontColor();
      padding: 0 5px;
    }

    .popper__arrow:after {
     border-bottom-color: rgba(0,0,0,0.60)!important;
    }
  }

</style>
